class MyBlockingQueue{
    private int[] items=new int[1000];
    //头标志
    volatile private int head=0;
    //尾标志
    volatile private int tail=0;
    //长度记录
    volatile private int size=0;
    //入队列
    synchronized public void put(int elem) throws InterruptedException {
        while (size==items.length){
            //队列满插入失败
            this.wait();
        }
        //将元素插入到tail的位置
        items[tail]=elem;
        tail++;
        //达到末尾重头再来
        if(tail==items.length){
            tail=0;
        }
        size++;
        this.notify();
    }
    //出队列
    synchronized public Integer take() throws InterruptedException {
        while (size==0){
            this.wait();
        }
        int value=items[head];
        head++;
        if(head==items.length){
            head=0;
        }
        size--;
        this.notify();
        return value;
    }
}
public class demo07 {
    //模拟实现阻塞队列
    public static void main(String[] args) {
        MyBlockingQueue queue=new MyBlockingQueue();
        Thread t1=new Thread(()-> {
            int value = 1;
            while (true) {
                try {
                    System.out.println("生产元素：" + value);
                    queue.put(value);
                    value++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();

        Thread t2=new Thread(()->{
            while (true) {
                try {
                    int value = queue.take();
                    System.out.println("消费元素：" + value);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t2.start();
    }
}
